package org.softmed.persistence;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.inject.Inject;

public class PersistenceManagerProvider {

	static Map<String, PersistenceProvider> providers = new HashMap<String, PersistenceProvider>();

	String providerName;

	static PersistenceProviderAnalyser persistenceProviderAnalyser = new PersistenceProviderAnalyser();

	public PersistenceManagerProvider() {

	}

	public PersistenceManagerProvider(String providerName) {
		this.providerName = providerName;
	}

	public PersistenceProvider getProvider(String providerName) {
		return providers.get(providerName);
	}

	public PersistenceManager getPersistenceManager() throws Throwable {
		return getPersistenceManager(providerName);
	}

	public String getProviderName() {
		return providerName;
	}

	public void setProviderName(String providerName) {
		this.providerName = providerName;
	}

	public PersistenceManager getPersistenceManager(String dbName)
			throws Throwable {
		PersistenceProvider provider = providers.get(dbName);
		if (provider == null)
			throw new RuntimeException("No ODBProvider was found for name "
					+ dbName);

		return provider.getPersistenceManager();
	}

	public static Map<String, PersistenceProvider> getProviders() {
		return providers;
	}

	public static void registerProvider(String name,
			PersistenceProvider provider) {
		providers.put(name, provider);
	}

	public static void clearProviderList() throws Throwable {
		providers.clear();
	}

	public static void stopProviders() throws Throwable {
		persistenceProviderAnalyser.stopProviders(providers.values());
	}

	public static void stopAndRefreshClassDefinitions() throws Throwable {
		stopProviders();
		refreshClassDefinitions();
		clearProviderList();
	}

	public static void refreshClassDefinitions() throws Throwable {
		persistenceProviderAnalyser.refreshClassDefinitions(providers.values());
	}

	public static void deleteDatabases(
			List<PersistenceProvider> providersToDelete) throws Throwable {
		persistenceProviderAnalyser.deleteDatabases(providersToDelete);
	}

	public static void deleteAllDatabases() throws Throwable {
		persistenceProviderAnalyser.deleteDatabases(providers.values());
	}
}
